App({
  onLaunch() {
    // 初始化音乐播放器
    this.initMusicPlayer();
  },

  globalData: {
    currentSong: null,
    isPlaying: false,
    playList: [],
    currentIndex: 0,
    playMode: 'sequence', // sequence, random, loop
    lyricData: []
  },

  initMusicPlayer() {
    // 创建背景音频管理器
    this.backgroundAudioManager = wx.getBackgroundAudioManager();
    
    // 监听音频事件
    this.backgroundAudioManager.onPlay(() => {
      this.globalData.isPlaying = true;
    });

    this.backgroundAudioManager.onPause(() => {
      this.globalData.isPlaying = false;
      this.stopProgressSimulation();
    });

    this.backgroundAudioManager.onStop(() => {
      this.globalData.isPlaying = false;
      this.stopProgressSimulation();
    });

    this.backgroundAudioManager.onEnded(() => {
      this.playNext();
    });

    // 监听音频进度更新
    this.backgroundAudioManager.onTimeUpdate(() => {
      this.globalData.currentTime = Math.floor(this.backgroundAudioManager.currentTime);
    });

    // 监听音频错误
    this.backgroundAudioManager.onError((error) => {
      console.error('音频播放错误:', error);
      wx.showToast({
        title: '音频播放错误',
        icon: 'none'
      });
    });
  },

  playSong(song) {
    if (!song || !song.url) return;

    this.globalData.currentSong = song;
    this.globalData.isPlaying = true;

    try {
      // 音频缓存优化：先尝试使用缓存
      const cachedUrl = this.cacheAudio(song);
      
      // 使用真实音频URL播放
      this.backgroundAudioManager.title = song.name;
      this.backgroundAudioManager.singer = song.artist;
      this.backgroundAudioManager.coverImgUrl = song.cover;
      this.backgroundAudioManager.src = cachedUrl || song.url;
      
      // 监听真实音频进度
      this.setupAudioProgressListener();
      
      // 添加到播放历史
      this.addToHistory(song);
      
    } catch (error) {
      console.error('播放音频失败:', error);
      wx.showToast({
        title: '播放失败，请检查网络或音频源',
        icon: 'none'
      });
    }
  },

  togglePlay() {
    if (this.globalData.isPlaying) {
      this.backgroundAudioManager.pause();
      this.stopProgressSimulation();
      this.globalData.isPlaying = false;
    } else {
      this.backgroundAudioManager.play();
      this.startProgressSimulation();
      this.globalData.isPlaying = true;
    }
  },

  playNext() {
    if (this.globalData.playList.length === 0) return;
    
    const nextIndex = (this.globalData.currentIndex + 1) % this.globalData.playList.length;
    this.globalData.currentIndex = nextIndex;
    this.playSong(this.globalData.playList[nextIndex]);
  },

  playPrev() {
    if (this.globalData.playList.length === 0) return;
    
    const prevIndex = (this.globalData.currentIndex - 1 + this.globalData.playList.length) % this.globalData.playList.length;
    this.globalData.currentIndex = prevIndex;
    this.playSong(this.globalData.playList[prevIndex]);
  },

  setPlayList(songs, index = 0) {
    this.globalData.playList = songs;
    this.globalData.currentIndex = index;
  },

  setupAudioProgressListener() {
    // 清除模拟进度计时器，使用真实音频进度
    this.stopProgressSimulation();
  },

  // 模拟播放进度
  startProgressSimulation() {
    if (this.progressTimer) {
      clearInterval(this.progressTimer);
    }
    
    this.progressTimer = setInterval(() => {
      if (this.globalData.isPlaying && this.globalData.currentSong) {
        // 模拟进度更新
        const currentTime = this.globalData.currentTime || 0;
        const duration = this.globalData.currentSong.duration || 300;
        
        if (currentTime < duration) {
          this.globalData.currentTime = currentTime + 1;
        } else {
          // 播放完成，自动下一首
          this.playNext();
        }
      }
    }, 1000);
  },

  stopProgressSimulation() {
    if (this.progressTimer) {
      clearInterval(this.progressTimer);
      this.progressTimer = null;
    }
  },

  // 播放模式切换
  switchPlayMode() {
    const modes = ['sequence', 'random', 'loop'];
    const currentMode = this.globalData.playMode;
    const currentIndex = modes.indexOf(currentMode);
    const nextMode = modes[(currentIndex + 1) % modes.length];
    
    this.globalData.playMode = nextMode;
    
    const modeNames = {
      'sequence': '顺序播放',
      'random': '随机播放',
      'loop': '单曲循环'
    };
    
    wx.showToast({
      title: modeNames[nextMode],
      icon: 'none'
    });
    
    return nextMode;
  },

  // 根据播放模式获取下一首歌曲
  getNextSong() {
    const { playList, currentIndex, playMode } = this.globalData;
    if (playList.length === 0) return null;

    switch (playMode) {
      case 'random':
        // 随机播放
        const randomIndex = Math.floor(Math.random() * playList.length);
        return { song: playList[randomIndex], index: randomIndex };
      
      case 'loop':
        // 单曲循环
        return { song: playList[currentIndex], index: currentIndex };
      
      case 'sequence':
      default:
        // 顺序播放
        const nextIndex = (currentIndex + 1) % playList.length;
        return { song: playList[nextIndex], index: nextIndex };
    }
  },

  // 根据播放模式获取上一首歌曲
  getPrevSong() {
    const { playList, currentIndex, playMode } = this.globalData;
    if (playList.length === 0) return null;

    switch (playMode) {
      case 'random':
        // 随机播放
        const randomIndex = Math.floor(Math.random() * playList.length);
        return { song: playList[randomIndex], index: randomIndex };
      
      case 'loop':
        // 单曲循环
        return { song: playList[currentIndex], index: currentIndex };
      
      case 'sequence':
      default:
        // 顺序播放
        const prevIndex = (currentIndex - 1 + playList.length) % playList.length;
        return { song: playList[prevIndex], index: prevIndex };
    }
  },

  // 更新播放下一首逻辑
  playNext() {
    const nextSongInfo = this.getNextSong();
    if (!nextSongInfo) return;
    
    this.globalData.currentIndex = nextSongInfo.index;
    this.playSong(nextSongInfo.song);
  },

  // 更新播放上一首逻辑
  playPrev() {
    const prevSongInfo = this.getPrevSong();
    if (!prevSongInfo) return;
    
    this.globalData.currentIndex = prevSongInfo.index;
    this.playSong(prevSongInfo.song);
  },

  // 加载歌词数据
  loadLyricData(song) {
    if (!song) return;
    
    const LyricParser = require('./utils/lyric-parser.js');
    const lyricData = LyricParser.generateMockLyric(song.name, song.duration);
    this.globalData.lyricData = lyricData;
    
    return lyricData;
  },

  // 获取当前播放的歌词
  getCurrentLyric(currentTime) {
    const lyricData = this.globalData.lyricData;
    if (!lyricData || lyricData.length === 0) return null;
    
    let currentLyric = null;
    for (let i = 0; i < lyricData.length; i++) {
      if (currentTime >= lyricData[i].time) {
        currentLyric = lyricData[i];
      } else {
        break;
      }
    }
    
    return currentLyric;
  },

  // 音频缓存优化
  cacheAudio(song) {
    if (!song || !song.url) return;
    
    // 检查是否支持缓存
    if (wx.getStorageSync) {
      const cacheKey = `audio_cache_${song.id || song.name}`;
      const cachedUrl = wx.getStorageSync(cacheKey);
      
      if (cachedUrl) {
        return cachedUrl;
      }
      
      // 模拟缓存过程
      setTimeout(() => {
        wx.setStorageSync(cacheKey, song.url);
      }, 1000);
    }
    
    return song.url;
  },

  // 分享功能
  shareSong(song) {
    if (!song) return null;
    
    return {
      title: `分享歌曲：${song.name} - ${song.artist}`,
      path: `/pages/index/index?songId=${song.id || song.name}`,
      imageUrl: song.cover
    };
  },

  // 添加到收藏
  addToFavorites(song) {
    if (!song) return false;
    
    try {
      const favorites = wx.getStorageSync('music_favorites') || [];
      const existingIndex = favorites.findIndex(fav => fav.id === song.id || fav.name === song.name);
      
      if (existingIndex === -1) {
        favorites.push({
          id: song.id || Date.now(),
          name: song.name,
          artist: song.artist,
          cover: song.cover,
          duration: song.duration,
          url: song.url,
          addTime: Date.now()
        });
        
        wx.setStorageSync('music_favorites', favorites);
        return true;
      }
    } catch (error) {
      console.error('添加到收藏失败:', error);
    }
    
    return false;
  },

  // 从收藏移除
  removeFromFavorites(song) {
    if (!song) return false;
    
    try {
      const favorites = wx.getStorageSync('music_favorites') || [];
      const filteredFavorites = favorites.filter(fav => 
        !(fav.id === song.id || fav.name === song.name)
      );
      
      if (filteredFavorites.length !== favorites.length) {
        wx.setStorageSync('music_favorites', filteredFavorites);
        return true;
      }
    } catch (error) {
      console.error('从收藏移除失败:', error);
    }
    
    return false;
  },

  // 检查是否已收藏
  isFavorite(song) {
    if (!song) return false;
    
    try {
      const favorites = wx.getStorageSync('music_favorites') || [];
      return favorites.some(fav => fav.id === song.id || fav.name === song.name);
    } catch (error) {
      console.error('检查收藏状态失败:', error);
    }
    
    return false;
  },

  // 获取收藏列表
  getFavorites() {
    try {
      return wx.getStorageSync('music_favorites') || [];
    } catch (error) {
      console.error('获取收藏列表失败:', error);
      return [];
    }
  },

  // 添加播放历史
  addToHistory(song) {
    if (!song) return;
    
    try {
      const history = wx.getStorageSync('music_history') || [];
      const existingIndex = history.findIndex(item => item.id === song.id || item.name === song.name);
      
      // 移除重复项
      if (existingIndex !== -1) {
        history.splice(existingIndex, 1);
      }
      
      // 添加到开头
      history.unshift({
        id: song.id || Date.now(),
        name: song.name,
        artist: song.artist,
        cover: song.cover,
        duration: song.duration,
        url: song.url,
        playTime: Date.now()
      });
      
      // 限制历史记录数量
      if (history.length > 50) {
        history.splice(50);
      }
      
      wx.setStorageSync('music_history', history);
    } catch (error) {
      console.error('添加播放历史失败:', error);
    }
  },

  // 获取播放历史
  getHistory() {
    try {
      const history = wx.getStorageSync('music_history') || [];
      // 添加时间格式化
      return history.map(item => ({
        ...item,
        playTime: this.formatTime(item.playTime)
      }));
    } catch (error) {
      console.error('获取播放历史失败:', error);
      return [];
    }
  },

  // 获取收藏列表
  getFavorites() {
    try {
      const favorites = wx.getStorageSync('music_favorites') || [];
      // 添加时间格式化
      return favorites.map(item => ({
        ...item,
        addTime: this.formatTime(item.addTime)
      }));
    } catch (error) {
      console.error('获取收藏列表失败:', error);
      return [];
    }
  },

  // 时间格式化函数
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    const now = Date.now();
    const diff = now - timestamp;
    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    
    if (diff < minute) {
      return '刚刚';
    } else if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前';
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前';
    } else if (diff < 7 * day) {
      return Math.floor(diff / day) + '天前';
    } else {
      const date = new Date(timestamp);
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
  },
});